package py.com.fms.fms.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports
import py.com.fms.fms.bean.CurrencyBean;
import py.com.fms.fms.bean.QuotationBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.persistence.services.CurrencyServices;
import py.com.fms.fms.persistence.services.QuotationServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ComAssistant;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.*;

@SuppressWarnings("unused")
@Name("editQuotation")
@Scope(ScopeType.SESSION)
public class EditQuotation {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	private DateAssistant dateAssist;

	// Attribute used for saving and deleting
	private QuotationBean quotation;
	
	// Services
	private QuotationServices qnSrv;
	private CurrencyServices crSrv;
	private UsersServices usSrv;
	
	// Collection of monedasBean
	private Collection<QuotationBean> allQuotations;

	// Attribute used for editing or updating
	private QuotationBean editQuotation;
	
//	Necessary Attributes;
	private CurrencyBean currencyDesc = null;
	private String currencyCod;
	private Long currencyId;
	
	
	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			
			if(credentials != null){
				System.out.println("Credenciales Encontradas");
				this.getUser().setUserName(credentials.getUsername());
				System.out.println("User Name: " + this.getUser().getUserName());
				user = usSrv.getUserDataByName(this.getUser().getUserName());
				this.setUser(user);
				System.out.println("User: " + this.getUser());
			}else{	
				System.out.println("Credenciales Nulas");
			}
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	public void cleanExternalAtt(){
		this.setCurrencyDesc(null);
	}
	
	public void initBeans(){
		
		if (quotation == null){
			quotation = new QuotationBean();
			quotation.setStatus(true);
		}
		
		if (editQuotation == null){
			editQuotation = new QuotationBean();
		}
		
		if (user == null){
			user = new UsersBean();
		}
		
	}
	
	public void initServices() throws CommonException{
		
		if (crSrv == null){
			crSrv = new CurrencyServices(this.sqlMap.getConfig());
		}
		
		if (qnSrv == null){
			qnSrv = new QuotationServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allQuotations == null){
			allQuotations = new ArrayList<QuotationBean>();
		}
		
	

	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			QuotationServices admSrv = new QuotationServices(this.sqlMap.getConfig());
			this.setAllQuotations(qnSrv.getAllQuotations());
			for (QuotationBean quotation : this.getAllQuotations()) {
				System.out.println("QUOTATION" + quotation.getStartDate());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public String cancelData() {
//		this.facesMessages.clear();
		this.setInitVar("S");
		return null;
	}

	// Used to UpperCase
	private String convertField(String data) {
		if (data == null) {
			return null;
		}
		return data.trim().toUpperCase();
	}
		

	// Used for data saving process
	public String saveNewData() throws ParseException {
		try {
			
			
//			this.facesMessages.clear();
			QuotationServices admSrv = new QuotationServices(this.sqlMap.getConfig());
			QuotationBean newCurrency = new QuotationBean();
			aid = new WithinHolder();
			this.today = DateAssistant.getCurrentDate();
			currencyCod = convert.getCurrencyCod(this.getCurrencyDesc());
			if (this.currencyCod == null){
				System.out.println("Currency Cod is null");
			}
			else{
				// Setting id value
				this.currencyId = crSrv.getIdCurrency(this.getCurrencyCod());
				if(this.currencyId == 0)
					System.out.println("Currency Id is null");
			}

			if (this.getQuotation() == null) {
				System.out.println("this.getQuotation() == null");
				throw new CommonException("Quotation doesn't exist");
			}
			System.out.println("BEFORE SETTING VALUES");
			// Setting field values
			newCurrency.setIdCurrency(this.getCurrencyId());
			newCurrency.setBuyAmount(this.getQuotation().getBuyAmount());
			newCurrency.setSaleAmount(this.getQuotation().getSaleAmount());
			newCurrency.setStatus(this.getQuotation().getStatus());
			newCurrency.setStartDate(this.today);
			System.out.println(this.today);
			newCurrency.setUserIns(user.getId());

			qnSrv.saveNewQuotation(newCurrency);
			
			// Initializing field values
			newCurrency = null;
			
			// Setting Initialization VAR
			
			return null;
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.setQuotation(null);
			this.cleanExternalAtt();
			this.setInitVar("S");
		}
		return "";
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (QuotationBean bean : this.getAllQuotations()) {
			if(bean.getId() == id){
				this.setEditQuotation(bean);
				this.setCurrencyDesc(convert.getCurrencyDesc(bean.getIdCurrency()));
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			currencyCod = convert.getCurrencyCod(this.getCurrencyDesc());
			currencyId = crSrv.getIdCurrency(this.getCurrencyCod());
			
			qnSrv.updateQuotation(this.getEditQuotation());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (QuotationBean bean: this.getAllQuotations()){
			if (bean.getId() == id) {
				try {
					
					qnSrv.deleteQuotationById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}
	
	// GETTERS AND SETTERS

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public QuotationBean getQuotation() {
		return quotation;
	}

	public void setQuotation(QuotationBean quotation) {
		this.quotation = quotation;
	}

	public Collection<QuotationBean> getAllQuotations() {
		return allQuotations;
	}

	public void setAllQuotations(Collection<QuotationBean> allQuotations) {
		this.allQuotations = allQuotations;
	}

	public QuotationBean getEditQuotation() {
		return editQuotation;
	}

	public void setEditQuotation(QuotationBean editQuotation) {
		this.editQuotation = editQuotation;
	}

	public CurrencyBean getCurrencyDesc() {
		return currencyDesc;
	}

	public void setCurrencyDesc(CurrencyBean currencyDesc) {
		this.currencyDesc = currencyDesc;
	}

	public String getCurrencyCod() {
		return currencyCod;
	}

	public void setCurrencyCod(String currencyCod) {
		this.currencyCod = currencyCod;
	}

	public Long getCurrencyId() {
		return currencyId;
	}

	public void setCurrencyId(Long currencyId) {
		this.currencyId = currencyId;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	
	
	

}
